package com.mjfeed.service.impl;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.mjfeed.service.MailService;

@Service("mailService")
public class MailServiceImpl implements MailService {
	
	private final static String SITENAME = "美嘉饲料"; 
	/** 默认发件人邮箱配置  */
	private final static String SMTPFROMMAIL = "service@mjfeed.cn"; 
	private final static String SMTPHOST = "smtp.exmail.qq.com"; 
	private final static Integer SMTPPORT = 25; 
	private final static String SMTPUSERNAME = "service@mjfeed.cn"; 
	private final static String SMTPPASSWORD = "mj10086"; 
	
	@Resource(name="javaMailSender")
	private JavaMailSenderImpl javaMailSender;
	
	@Resource(name = "taskExecutor")
	private TaskExecutor taskExecutor;

	/**
	 * 添加邮件发送任务
	 * 
	 * @param mimeMessage
	 *            MimeMessage
	 */
	private void addSendTask(final MimeMessage mimeMessage) {
		try {
			taskExecutor.execute(new Runnable() {
				public void run() {
					javaMailSender.send(mimeMessage);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void send(String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername, String smtpPassword, String toMail, String subject, String text, boolean async) {
		Assert.hasText(smtpFromMail);
		Assert.hasText(smtpHost);
		Assert.notNull(smtpPort);
		Assert.hasText(smtpUsername);
		Assert.hasText(smtpPassword);
		Assert.hasText(toMail);
		Assert.hasText(subject);
		Assert.hasText(text);
		
		try {
			javaMailSender.setHost(smtpHost);
			javaMailSender.setPort(smtpPort);
			javaMailSender.setUsername(smtpUsername);
			javaMailSender.setPassword(smtpPassword);
			MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper mimeMessageHelper;
			mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
			mimeMessageHelper.setFrom(MimeUtility.encodeWord(SITENAME) + " <" + smtpFromMail + ">");
			mimeMessageHelper.setSubject(subject);
			mimeMessageHelper.setTo(toMail);
			mimeMessageHelper.setText(text, true);
			if (async) {
				addSendTask(mimeMessage);
			} else {
				javaMailSender.send(mimeMessage);
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void send(String toMail, String subject, String text, boolean async) {
		send(SMTPFROMMAIL, SMTPHOST, SMTPPORT, SMTPUSERNAME, SMTPPASSWORD, toMail, subject, text, async);
	}
}
